﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Net;
using System.IO;

namespace EuroAudit
{
    public partial class DocByLink : System.Web.UI.Page
    {
        string[] DLink = null;
        GlobalF GFunc = new GlobalF();

        protected void Page_Load(object sender, EventArgs e)
        {
            GFunc.InitO();

            NameValueCollection HRStr = Request.QueryString;
            if (HRStr.GetValues("DocLink") != null)
            {
                DLink = HRStr.GetValues("DocLink");
                txtLink.Text = DLink[0].ToString();
                LoadDoc(txtLink.Text);
            }
        }
        void LoadDoc(string Link)
        {
            //atrodam faila ceļu uz FTP no datubāzes ieraksta
            DataSet dsFile;
            DataSet dsOrg;
            string FilePath;
            string OrgID;
            string OrgName;
            string DocType;
            string DocName;

            dsFile = GFunc.GetData("SELECT OrgID, DocType, DocName FROM doc WHERE RecStatus=0 AND Link='" + Link + "'", "WebCNS", false);
            if (dsFile.Tables.Count > 0)
            {
                if (dsFile.Tables[0].Rows.Count > 0)
                {
                    OrgID = dsFile.Tables[0].Rows[0]["OrgID"].ToString();
                    DocType = dsFile.Tables[0].Rows[0]["DocType"].ToString();
                    DocName = dsFile.Tables[0].Rows[0]["DocName"].ToString();
                    dsOrg = GFunc.GetData("SELECT OrgName FROM org WHERE RecStatus=0 AND OrgID='" + OrgID + "'", "WebCNS", false);
                    if (dsOrg.Tables.Count > 0)
                    {
                        if (dsOrg.Tables[0].Rows.Count > 0)
                        {
                            OrgName = dsOrg.Tables[0].Rows[0]["OrgName"].ToString();
                        }
                        else
                        {
                            lblMessage.Text = "Fails nav atrasts.";
                            return;
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Fails nav atrasts.";
                        return;
                    }
                }
                else
                {
                    lblMessage.Text = "Fails nav atrasts.";
                    return;
                }
            }
            else
            {
                lblMessage.Text = "Fails nav atrasts.";
                return;
            }

            FilePath = GlobalF.AppOptions["FTP server"] + OrgName + "/" + DocType + "/" + DocName;
            FtpWebRequest requestFS = (FtpWebRequest)WebRequest.Create(FilePath);
            requestFS.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);
            //pieprasam faila izmēru
            requestFS.Method = WebRequestMethods.Ftp.GetFileSize;
            FtpWebResponse FTPResponseFS = (FtpWebResponse)requestFS.GetResponse();
            FTPResponseFS.GetResponseStream();
            long FileSize = 1024;// FTPResponseFS.ContentLength;
            //pieprasam failu
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FilePath);
            request.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            FtpWebResponse FTPResponse = (FtpWebResponse)request.GetResponse();
            /*//FTPResponse.GetResponseStream();
            
            //FTPResponse.ContentType;
            //long FileSize = FTPResponse.GetResponseStream().Length;
            byte[] Buffer = new byte[(int)FileSize];
            Response.ContentType = "application/pdf"; //FTPResponse.ContentType;
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + DocName);
            while (true)
            {
                int BRead = FTPResponse.GetResponseStream().Read(Buffer, 0, (int)FileSize);
                if (BRead == 0)
                {
                    break;
                }
                else
                {
                    Response.BinaryWrite(Buffer);
                }
            }
            Response.End();
             */
            byte[] Buffer = new byte[(int)FileSize];
            string ServerPath = Server.MapPath(null) + "\\Temp";
            Stream FTPStream = FTPResponse.GetResponseStream();
            //FileStream outputStream = new FileStream(ServerPath + "\\" + DocName, FileMode.Create);
            int readCount = FTPStream.Read(Buffer, 0,(int)FileSize);
            Response.Clear();
            Response.BufferOutput = true;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + DocName);
            while (readCount > 0)
            {
                //outputStream.Write(Buffer, 0, readCount);
                //Response.BinaryWrite(Buffer);
                Response.OutputStream.Write(Buffer, 0, readCount);
                readCount = FTPStream.Read(Buffer, 0, (int)FileSize);
            }
            FTPStream.Close();
            //outputStream.Close();
            Response.Flush();
            Response.End();
            //Response.TransmitFile("Temp\\" + DocName);
            //Response.BufferOutput = true;
            //Response.Redirect("Temp\\" + DocName, false);
            //Response.Flush();
            //System.IO.File.Delete(ServerPath + "\\" + DocName);
            
            //Stream responseStream = FTPResponse.GetResponseStream();
            //StreamReader reader = new StreamReader(responseStream);
            
        }

        protected void cmdShow_Click(object sender, EventArgs e)
        {
            LoadDoc(txtLink.Text);
        }
    }
}
